<?php
//+-----------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+-----------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+-----------------------------------------------------------
//| 
//+-----------------------------------------------------------


namespace app\admin\service;


use app\admin\exception\LogicException;
use app\admin\model\Menu as Model;
use app\admin\validate\MenuValidate;
use think\db\exception\PDOException;
use think\facade\Request;

/**
 * MenuService
 * @package app\admin\service
 * @property \app\admin\model\Menu $model
 * @property MenuValidate $validate
 */
class Menu extends AdminService
{

    /**
     * 初始化
     */
    protected function init(){
        $this->model = new Model();
        $this->validate = new MenuValidate();
    }

    /**
     * 获取菜单树
     * @return array|mixed|object|\think\App
     */
    public function getTreeMenu(){
    	if(session('?SYSTEM_ID') && session('SYSTEM_ID') == 1){
		    return $this->model->getTreeMenu();
	    }else if(session('?SYSTEM_ID')){
			return Auth::instance()->getRuleMap(session('SYSTEM_ID'),true);
	    }
    }

    /**
     * 获取当前菜单名 标签库用了
     * @return array
     */
    public function getCurrentMenu(){
        $controller = Request::controller();
        $action = Request::action();
        try{
            $second = $this->model->deleted(false)->where(['controller'=>$controller,'action'=>$action])->field('name,link,pid,id')->find();
            if(!$second){
                $second = ['name'=>'未知','link'=>'','id'=>0,'pid'=>0];
            }else{
                $second = $second->toArray();
            }

            $id = $second['pid'];
            $where = $id<=0?['controller'=>$controller]:['id'=>$id];
            $first = $this->model->where($where)->deleted(false)->field('name,link,pid,id')->find();
            $first = $first->toArray();
            return [ $first, $second];
        }catch (PDOException $e){
            $menu = include app()->getConfigPath().'menu.php';
        }
    }

    /**
     * 数据表格需要的数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTableList($where = []){
        $name = $this->request->post('name/s','');
        $show = $this->request->post('show/s','');
        if(!empty($name)){
            $where = ['name','like',"%$name%"];
        }else{
            $where = [];
        }

        $query = $this->model->where($where);
        $count = $query->count();
        $list = $query->deleted(false)->field('id,name,controller,action,link,createtime,updatetime,icon,pid')
            ->order(['sort'=>'asc','is_show'=>'desc'])
            ->select();

        if($list){
            $list = $list->toArray();
        }else{
            $list = [];
        }

        return json([
            'code' => 0,
            'count' => $count,
            'data' => $list,
            'msg' => ''
        ]);
    }

    /**
     * 获取下拉组件需要的数据
     * @return \think\response\Json
     */
    public function getSelectTree(){
        $pid = $this->request->get('pid/d',0);
        $list =  $this->model->deleted(false)->field('id,name,pid')->order('sort asc')->select();
        if($list ){
            $list  = $list->toArray();
        }else{
            return json([]);
        }

        $alist = array_map(function($item)use($pid){
            $item['open'] = true;
	        $item['checked'] = $item['id'] == $pid?true:false;
            return $item;
        },$list);

		unset($list);
        $list = recursion($alist);
        $list[-1] = [
            'checked'=> false,
            'id'=> 0,
            'name'=> "顶级菜单",
            'open'=> true,
            'pid'=> 0,
        ];
        sort($list);
        return json($list);
    }

    /**
     * 角色选择权限节点
     * @return array|mixed|object|\think\App
     */
    public function getTreeComponets(){
        return $this->model->getTreeComponets();
    }

	public function delete($where = []){
		if($this->request->isGet()){
			$ids[] = $this->request->get('id');
		}else{
			$ids = $this->request->post('ids');
		}
		if($this->model->where('id|pid','in',$ids)->update(['deletetime'=>time()])){
			return $this->success('操作成功:删除');
		}
		throw new LogicException('操作失败:删除');
	}
}